//
//  SetNameViewController.swift
//  fsapp
//
//  Created by ly on 2017/9/21.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import Alamofire
import SnapKit
import SVProgressHUD
import WCLImagePickerController
import AliyunOSSiOS


class SetNameViewController: UIViewController,WCLImagePikcerDelegate{

    
    let  setview = loginView(type: "1")
    //上传图片所需变量
    fileprivate var imageupload = NSData()
    fileprivate var upjudge = false
    fileprivate var client:OSSClient?
    fileprivate var imgUrl:String?
    
    
    lazy var textView : UITextField = {
        let textView = UITextField()
        textView.layer.cornerRadius = 3
        textView.layer.borderWidth = 1
        textView.font = UIFont.systemFont(ofSize: 28)
        textView.placeholder = "在此输入"
        // textView.textColor = title2color
        return textView
    }()
    
    lazy var submit: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = naviColor
        btn.setTitle("提交", for: .normal)
        btn.layer.cornerRadius = 10
        return btn;
    }()
    
    
    lazy var returnButton:UIButton = {
        let btn = UIImageView()
        //imgV.frame = CGRectMake(WIDTH(23), HEIGHT(62), WIDTH(25), HEIGHT(45));
        
        btn.frame = CGRect(x: getWidth(width: 24), y: CGFloat(getHeight(22)), width: getWidth(width: 25), height: getHeight(45));
        btn.image = UIImage(named:"return")
        let back = UIButton()
        back.frame = CGRect(x: getWidth(width: 0), y: CGFloat(getHeight(0)), width: getWidth(width: 70), height: getHeight(128));
        back.addSubview(btn)
        return back
    }()
    
    
    fileprivate lazy var ImageButton:UIButton = {
       let button = UIButton()
       button.setImage(#imageLiteral(resourceName: "头像"), for: .normal)
       button.layer.cornerRadius = 20
       button.layer.masksToBounds = true
       return button
    
    }()
    
    fileprivate lazy var imageLabel:UILabel = {
       let label = UILabel()
       label.text = "上传头像"
       label.font = UIFont.systemFont(ofSize: getHeight(26))
       label.sizeToFit()
       return label
    
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(setview.accountLabel)
        self.view.addSubview(setview.accountText)
        self.view.addSubview(setview.loginNow)
        self.view.addSubview(ImageButton)
        self.view.addSubview(imageLabel)
        setUI()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - imagePick 协议实现 
    func wclImagePickerCancel(_ picker: WCLImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func wclImagePickerComplete(_ picker: WCLImagePickerController, imageArr: [UIImage]) {
        picker.dismiss(animated: true, completion: nil)
        
        for i in imageArr{
            self.ImageButton.setImage(i, for: .normal);
            imageupload = i.compressImage(image: i, maxLength: 1024*1024)!
        }
        
        if imageArr.count == 0{
            self.upjudge = false
        }else{
            self.upjudge = true
        }
  
    }
    
    func wclImagePickerError(_ picker: WCLImagePickerController, error: WCLError) {
        let al = UIAlertController.init(title: nil, message: error.lcalizable, preferredStyle: .alert)
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        al.addAction(cancel)
        picker.present(al, animated: true, completion: nil)
        
    }
    
    func touchesPick(){
        WCLImagePickerController.present(inVC: self, delegate: self)
        WCLImagePickerOptions.maxPhotoSelectNum = 1
    }

    
    
    
    
    
    func setUI(){
        self.view.backgroundColor = UIColor.white
        self.tabBarController?.tabBar.isHidden = false
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        //标题颜色
        self.navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        self.navigationItem.title = "编辑资料"
        self.navigationController?.navigationBar.isTranslucent = false
        
        self.navigationController?.navigationBar.barTintColor = naviColor
        //  let item = UIBarButtonItem(self.returnButton)
        
        self.navigationController?.navigationBar.addSubview(returnButton)
        self.returnButton.addTarget(self, action: #selector(touchPop), for: .touchUpInside)
        
        self.ImageButton.snp.makeConstraints{(make) in
            make.left.equalTo(setview.accountText.snp.left)
            make.bottom.lessThanOrEqualTo((setview.accountText.snp.top)).offset(-30)
            make.height.equalTo(40)
            make.width.equalTo(40)
        
        }
        self.imageLabel.snp.makeConstraints{(make) in
            
            make.left.equalTo(setview.accountLabel.snp.left)
            make.bottom.lessThanOrEqualTo(setview.accountText.snp.top).offset(-40)
            
        }
        
        self.ImageButton.addTarget(self, action: #selector(touchesPick), for: .touchUpInside)
        self.setview.loginNow.addTarget(self, action: #selector(update), for: .touchUpInside)

        
        
        
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //self.textView.resignFirstResponder()
        self.setview.accountText.resignFirstResponder()
    }
    
    func touchPop(){
        self.dismiss(animated: true, completion: nil)
    }
    
    
    
    func Alarequest(img:String?){
        let url = "http://dahan-api.heiyou.net/index.php/home/user/EditData"
        let content = self.setview.accountText.text!
        
        if content == ""
        {
            SVProgressHUD.showError(withStatus: "请输入内容")
            SVProgressHUD.dismiss(withDelay: 1)
            return
        }
        loadCookies()
        //let usd = UserDefaults.standard
        var imgg = ""
        
        if let  o = img{
            imgg = o
        }
        
        
//        if let img = usd.object(forKey: "img"){
//            imgg = img as! String
//        }
        let paramdic = ["name":content,"img":imgg,"sex":""]
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if let al = response.response{
                
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
            }
            
            //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                // print(js)
               // print(content)
                SVProgressHUD.dismiss(withDelay: 2)
                if js["status"] == 200{
                    
                    //let vc  = LoadViewController()
                    //vc.Alarequest()
                    SVProgressHUD.showSuccess(withStatus: "修改成功！")
                    self.dismiss(animated: true, completion: nil)
                    
                    
                }else {
                    SVProgressHUD.showError(withStatus: js["msg"].string!)
                }
                
            }
        }
        
    }
    
    
    func initALi() {
        
        
        
        let endpoint:String =  "http://oss-cn-shenzhen.aliyuncs.com"
        let accesskeyId = "zlN0arcl6DMQpBTf"
        let accesskeySecret = "STDVRcq9CmVa7J6Iv2Y4l4LMweG48A"
        let credential: OSSCredentialProvider = OSSCustomSignerCredentialProvider {(contentToSign, error: NSErrorPointer) -> String? in
            
            let signture = OSSUtil.calBase64Sha1(withData: contentToSign, withSecret: accesskeySecret)
            if signture == nil {
                print(error!)
                return nil
            }
            return "OSS \(accesskeyId):\(signture!)"
        }
        
        client = OSSClient(endpoint: endpoint, credentialProvider: credential)
        
        //       let clientConfig = ClientConfiguration()
        //        clientConfig.connection_timetout = 30
        //        clientConfig.retry_time = 3
        //        client = OSSClient(endpoint: endpoint, accessKeyId: accesskeyId, accessKeySecret: accesskeySecret,  config: clientConfig)
        
        // let credential: OSSCredentialProvider = OSSPlainTextAKSKPairCredentialProvider(plainTextAccessKey: "zlN0arcl6DMQpBTf", secretKey: "STDVRcq9CmVa7J6Iv2Y4l4LMweG48A")
        // let conf = OSSClientConfiguration()
        //网络请求遇到异常失败后重复的次数
        // conf.maxRetryCount = 3
        //网络请求超时事件
        // conf.timeoutIntervalForRequest = 30
        //允许资源传输的最长时间
        //conf.timeoutIntervalForResource = TimeInterval(24 * 60 * 60)
        //阿里地址
        // client = OSSClient(endpoint: "http://oss-cn-shenzhen.aliyuncs.com", credentialProvider: credential)
    }
    
    
    
    func update() {
        
        initALi()
        //
        var date = Date(timeIntervalSinceNow: 0)
        var data = self.imageupload
        
        let a: TimeInterval = date.timeIntervalSince1970
        let x = Int(a)
        date = Date()
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        formatter.dateFormat = "YYYY-MM-dd"
        let dateTime: String = formatter.string(from: date)
        let objectKey: String = "Picture/head/\(dateTime)/\(Int(x))_\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10).jpg"
        let str: String = "http://img.dahan.cn/\(objectKey)"
        imgUrl = "http://dahan-img.oss-cn-shenzhen.aliyuncs.com/\(objectKey)"
        //let vc = _2RegistViewController.init(Code, phone)
       self.Alarequest(img: imgUrl)
        // self.Alarequest2(data: imgUrl!, password: password, name: Name)
        print(imgUrl)
        let put = OSSPutObjectRequest.init()
        put.objectKey = objectKey
        put.uploadingData = data as Data!
        put.bucketName = "dahan-img"
        put.uploadProgress = {(_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void in
            print("\(bytesSent),\(totalBytesSent),\(totalBytesExpectedToSend)")
        }
        // PutObjectRequest(bucketName: "dahan-img", key: objectKey, data: data)
        
        client?.putObject(put)
        
        //        client?.putObject(request: put, onCompletion: {
        //            (success,result,error) in
        //            if success {
        //                 print("上传成功")
        //            }else{
        //               print(error ?? "" as! Error)
        //            }
        //
        //        })
        ////
        //        // put.objectKey = objectKey
        //       // put.uploadingData = data
        //      //  put.uploadProgress = {(_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void in
        //      //      print("\(bytesSent),\(totalBytesSent),\(totalBytesExpectedToSend)")
        //      //  }
        
    }
    

//MARK: - AliyunOSS
    
    
 //   func initALi() {
//
//        let endpoint:String =  "http://oss-cn-shenzhen.aliyuncs.com"
//        let accesskeyId = "zlN0arcl6DMQpBTf"
//        let accesskeySecret = "STDVRcq9CmVa7J6Iv2Y4l4LMweG48A"
//        let clientConfig = ClientConfiguration()
//        clientConfig.connection_timetout = 30
//        clientConfig.retry_time = 3
//        client = OSSClient(endpoint: endpoint, accessKeyId: accesskeyId, accessKeySecret: accesskeySecret,  config: clientConfig)
//
        // let credential: OSSCredentialProvider = OSSPlainTextAKSKPairCredentialProvider(plainTextAccessKey: "zlN0arcl6DMQpBTf", secretKey: "STDVRcq9CmVa7J6Iv2Y4l4LMweG48A")
        // let conf = OSSClientConfiguration()
        //网络请求遇到异常失败后重复的次数
        // conf.maxRetryCount = 3
        //网络请求超时事件
        // conf.timeoutIntervalForRequest = 30
        //允许资源传输的最长时间
        //conf.timeoutIntervalForResource = TimeInterval(24 * 60 * 60)
        //阿里地址
        // client = OSSClient(endpoint: "http://oss-cn-shenzhen.aliyuncs.com", credentialProvider: credential)
  //  }
    
    
    
  //  func update() {
        
//        initALi()
//        //put.bucketName = "dahan-img"
//        var date = Date(timeIntervalSinceNow: 0)
//        var data = self.imageupload
//        let a: TimeInterval = date.timeIntervalSince1970
//        let x = Int(a)
//        date = Date()
//
//        let formatter = DateFormatter()
//        formatter.dateStyle = .medium
//        formatter.timeStyle = .short
//        formatter.dateFormat = "YYYY-MM-dd"
//        let dateTime: String = formatter.string(from: date)
//        let objectKey: String = "Picture/head/\(dateTime)/\(Int(x))_\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10).jpg"
//        let str: String = "http://img.dahan.cn/\(objectKey)"
//        imgUrl = "http://dahan-img.oss-cn-shenzhen.aliyuncs.com/\(objectKey)"
//        //let vc = _2RegistViewController.init(Code, phone)
//       // self.Alarequest(data: imgUrl!, password: password, name: Name)
//        self.Alarequest(img: imgUrl)
//        print(imgUrl)
//        let put = PutObjectRequest(bucketName: "dahan-img", key: objectKey, data: data as Data)
//
//        client?.putObject(request: put, onCompletion: {
//            (success,result,error) in
//            if success {
//                print("上传成功")
//            }else{
//                print(error ?? "" as! Error)
//            }
//
//        })
//
  //  }
    
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
